<!--
 * @Author: 四川华西绿舍建材有限公司
 * @Date: 2023-11-28 16:21:47
 * @LastEditors: 陈波
 * @LastEditTime: 2024-03-16 22:46:05
 * @Description: 
 * @FilePath: \graDesign\src\views\SystemManagement\RoleManagement\index.vue
-->
<template>
  <div>
    <LayoutIndex>
      <BasicDescriptions :dataList="descriptionList" size="default" />
    </LayoutIndex>
    <LayoutIndex>
      <div class="mainF">
        <!-- <div class="treeF">
          <el-tree
            class="tree-line"
            :data="treeData"
            :props="defaultProps"
            :icon="CaretRight"
            @node-click="handleNodeClick"
          />
        </div> -->
        <div class="tableF" style="position: relative; overflow: hidden">
          <vxe-grid 
            ref="xGrid" 
            v-bind="gridOptions" 
            @page-change="handlePageChange"
          >
            <template #toolbar_buttons>
              <vxe-button @click="zoomEvent">切换表格最大化/还原</vxe-button>
              <button class="distribution" @click="distributeUser">分配用户</button>
            </template>
            <template #ismanager_edit="{ row }">
              {{ identity(row) }}
            </template>
            <template #status_edit="{ row }">
              {{ row.status == 1 ? '启用' : '禁用' }}
            </template>
          </vxe-grid>
        </div>
      </div>
    </LayoutIndex>
    <BasicDialog
      :visible="dialogVisible"
      title="分配角色"
      width="55%"
      :showClose="true"
      @handleClose="close"
    >
      <div class="content">
        <div class="flex_start">
          <el-text class="mx-1">可操作性：</el-text>
          <el-rate
            v-model="starValue"
            :texts="['差', '较差', '一般', '较强', '强']"
            show-text
            disabled
          />
        </div>
        <!-- 主内容区域 -->
        <div class="transformerBox">
          <div class="left_users">
            <div class="title">
              <h3 style="color: #000;">用户</h3>
            </div>
            <div class="search">
              <el-input 
                v-model="userSearch" 
                placeholder="请输入内容"
                :prefix-icon="Search"
                @input="userSearchChange"
               />
            </div>
            <div class="userTree" v-loading="userTreeLoading">
              <el-tree
                class="tree-line"
                :data="userTreeData"
                :props="defaultProps"
                :icon="CaretRight"
                :highlight-current="true"
                @node-click="handleUserNodeClick"
              />
            </div>
          </div>
          <div class="right_roles">
            <div class="title">
              <h3 style="color: #000;">角色</h3>
            </div>
            <div class="search">
              <el-input 
                v-model="roleSearch" 
                placeholder="请输入内容"
                :prefix-icon="Search"
               />
            </div>
            <div class="role-box">
              <el-empty v-if="roleIsEmpty" :image-size="200" />
              <div class="radios" v-else>
                <div class="radio-item">
                  <vxe-radio 
                    v-model="roleRadio" 
                    :label="0"
                    content="普通用户"
                    :disabled="t"
                  />
                </div>
                <div class="radio-item">
                  <vxe-radio 
                    v-model="roleRadio" 
                    :label="1"
                    content="管理人员"
                    :disabled="t"
                  />
                </div>
                <div class="radio-item">
                  <vxe-radio
                    v-model="roleRadio" 
                    :label="2"
                    content="超级管理员"
                    :disabled="notSuperManager"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取 消</el-button>
          <el-button type="success" @click="save()">保 存</el-button>
        </span>
      </template>
    </BasicDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, onMounted, reactive, computed, watch, inject, watchEffect } from 'vue'
import { VxeGridInstance, VxeGridProps } from 'vxe-table'
import { User, CaretRight, Search } from '@element-plus/icons-vue'
// api
import userApi from "@/request/api/user";
import { showMessageBox } from "@/utils/alertMsg";
import BasicDescriptions from '@/components/BasicDescriptions/index.vue';
import useLoginStore from "@/store/login";
import { storeToRefs } from 'pinia';

const loginStore = useLoginStore();
const { userInfo } = storeToRefs(loginStore);

const reload: Function = inject('reload')

let descriptionList = ref([])
const starValue = ref<number>(0)
onMounted(() => {
  descriptionList.value = [
    {
      label: '超级管理员',
      value: '拥有系统所有权限，可管理和分配超级管理员以及管理员身份',
      icon: shallowRef(User),
      span: 2,
      width: 280,
      align: 'left'
    },
    {
      label: '管理员',
      value: '拥有系统所有权限，可管理和分配管理员身份',
      icon: shallowRef(User),
      span: 2,
      align: 'left'
    },
    {
      label: '用户',
      value: '仅拥有系统数据的测试输入、观看图表权限，不可管理其他任何账号',
      icon: shallowRef(User),
      span: 2,
      align: 'left'
    }
  ]
  if(userInfo.value.ismanager == 2) {
    // 超级管理员，可操作性强
    starValue.value = 5;
  } else if(userInfo.value.ismanager == 1) {
    // 管理员，操作性较强
    starValue.value = 4;
  } else if(userInfo.value.ismanager == 0) {
    // 普通用户，操作性一般
    starValue.value = 3;
  }
});

const identity = computed(() => {
  return (row: any) => {
    let str: string = '';
    if(row.ismanager == 0) {
      str = '用户';
    } else if (row.ismanager == 1) {
      str = '管理员';
    } else if (row.ismanager == 2) {
      str = '超级管理员';
    }
    return str;
  }
})


let indicator = ref<number>(2);
const xGrid = ref<VxeGridInstance<any>>()
const gridOptions = reactive<VxeGridProps<any>>({
  border: true,
  showOverflow: true,
  showFooter: true,
  height: 530,
  columnConfig: {
    resizable: true
  },
  pagerConfig: {
    enabled: true,
    currentPage: 1,
    pageSize: 5,
    pageSizes: [1, 5, 10, 20, 30, 40, 50],
    perfect: true
  },
  toolbarConfig: {
    perfect: true,
    refresh: true,
    zoom: true,
    custom: true,
    slots: {
      // 自定义插槽模板
      buttons: 'toolbar_buttons'
    }
  },
  proxyConfig: {
    props: {
      result: 'result', // 配置响应结果列表字段
      total: 'page.total' // 配置响应结果总页数字段
    },
    ajax: {
      query: () => findList(indicator.value)
    }
  },
  columns: [
    { type: 'seq', width: 60 },
    { field: 'username', title: '用户名' },
    { field: 'phone', title: '手机号' },
    { field: 'ismanager', title: '身份', editRender: {}, slots: { default: 'ismanager_edit' } },
    { field: 'status', title: '状态', editRender: {}, slots: { default: 'status_edit' } }
  ],
  footerMethod ({ columns, data }) {
    const sums: any[] = []
    columns.forEach((column, columnIndex) => {
      // if (columnIndex === 0) {
      //   sums.push('平均')
      // } else {
      //   if (column.field === 'age') {
      //     sums.push(meanNum(data, 'age'))
      //   } else {
      //     sums.push('-')
      //   }
      // }
      sums.push('-')
    })
    // 返回一个二维数组的表尾合计
    return [sums]
  }
})
const findList = (type: number): Promise<{
  page: {
    total: number
  },
  result: any[]
}> => {
  return new Promise(resolve => {
    const params = {
      page: gridOptions.pagerConfig.currentPage,
      pageSize: gridOptions.pagerConfig.pageSize,
      type,
    };
    userApi.getUsersList(params).then((res: any) => {
      if (res.code == 200) {
        const rest = {
          page: {
            total: res.data.total
          },
          result: res.data.userList
        }
        resolve(rest)
      } else {
        showMessageBox("error", res.msg);
      }
    });
  })
}

const zoomEvent = () => {
  const $grid = xGrid.value
  if ($grid) {
    $grid.zoom()
  }
}

const handlePageChange = ({ currentPage, pageSize }) => {
  gridOptions.pagerConfig.currentPage = currentPage
  gridOptions.pagerConfig.pageSize = pageSize
  findList(indicator.value)
}

// ================================================

interface Tree {
  label: string;
  children?: Tree[];
  userid?: number
}

const userTreeData = ref<Tree[]>();

const defaultProps = {
  children: "children",
  label: "label",
};

let dialogVisible = ref<boolean>(false)
const close = () => {
  dialogVisible.value = false
}

let userTreeLoading = ref<boolean>(false)
const distributeUser = () => {
  dialogVisible.value = true;
  userTreeLoading.value = true;
  const params = {
    page: 1,
    pageSize: 99999,
    type: 2
  }
  userApi.getUsersList(params).then((res: any) => {
    if (res.code == 200) {
      let tempArr = []
      res.data.userList.forEach(item => {
        const target = {
          userid: item.userid,
          label: item.username
        }
        tempArr.push(target)
      })
      userTreeData.value = tempArr
    } else {
      showMessageBox("error", res.msg);
    }
  }).finally(() => {
    userTreeLoading.value = false;
  });
}

let roleIsEmpty = ref<boolean>(true)
const roleRadio = ref<number>(0);
const targetUser = ref<Tree>();
let map = new Map();

// map.set('1陈波Eternity', 2);
// map.set('2Supon_Li', 1);
// map.set('3豪仔AA', 0);
// map.set('4陈波T', 0);
// map.set('10testUser6', 0);

watch(() => dialogVisible.value, (newValue: boolean, oldValue: boolean) => {
  roleIsEmpty.value = true;
  if (newValue && newValue !== oldValue) {
    userApi.getUserRoles().then((res: any) => {
      if(res.code == 200) {
        for (const [key, value] of Object.entries(res.data)) {
          map.set(key, value);
        }
      } else {
        showMessageBox("error", res.msg);
      }
    })
  }
}, { immediate: true  })

// onMounted(() => {
//   userApi.getUserRoles().then((res: any) => {
//     if(res.code == 200) {
//       for (const [key, value] of Object.entries(res.data)) {
//         map.set(key, value);
//       }
//     } else {
//       showMessageBox("error", res.msg);
//     }
//   })
// })

const notSuperManager = computed(() => {
  return userInfo.value.ismanager != 2;
})

const hasBeAllowdOperation = computed(() => {
  return (ismanager?: number) => {
    return notSuperManager.value && ismanager == 2;
  }
})
let t = ref<boolean>(false);

const handleUserNodeClick = (data: Tree) => {
  roleIsEmpty.value = false;
  targetUser.value = data;
  const targetKey = data.userid + data.label;
  if(map.has(targetKey)) {
    t.value = hasBeAllowdOperation.value(map.get(targetKey));
    switch(map.get(targetKey)) {
      case 0: roleRadio.value = 0; break;
      case 1: roleRadio.value = 1; break;
      case 2: roleRadio.value = 2; break;
      default: roleRadio.value = 0; break;
    }
  }
  // userApi.getUserRoleByUserId({
  //   userid: data.userid
  // }).then((res: any) => {
  //   if(res.code == 200) {
  //     let key = data.userid + data.label;
  //     map.set(key, res.data.auth);
  //     switch(res.data.auth) {
  //       case 0: roleRadio.value = 0; break;
  //       case 1: roleRadio.value = 1; break;
  //       case 2: roleRadio.value = 2; break;
  //       default: roleRadio.value = 0; break;
  //     }
  //     console.log('map', map)
  //   } else {
  //     showMessageBox("error", res.msg);
  //   }
  // })
}

watch(() => roleRadio.value, (newVal: number) => {
  const targetKey = targetUser.value.userid + targetUser.value.label;
  switch(newVal) {
    case 0: map.set(targetKey, 0); break;
    case 1: map.set(targetKey, 1); break;
    case 2: map.set(targetKey, 2); break;
    default: map.set(targetKey, 0); break;
  }
})

/**
 * @description: 将Map转换为对象
 * @param {*} strMap
 * @return {*} obj
 */
function _strMapToObj(strMap){
  let obj= Object.create(null);
  for (let[k,v] of strMap) {
    obj[k] = v;
  }
  return obj;
}

const save = () => {
  // alert('save')
  const result = _strMapToObj(map);
  userApi.editUserRoles(result).then((res: any) => {
    if(res.code == 200) {
      showMessageBox("success", res.msg);
      close();
      loginStore.getAndSetUserInfo();
      setTimeout(() => {
        reload()
      }, 200)
    } else {
      showMessageBox("error", res.msg);
    }
  })
}

let userSearch = ref<string>('')
let roleSearch = ref<string>('')

const userSearchChange = () => {
  // console.log('userSearchChange:', userSearch.value)
  // 如果为空，则请求全部用户
  if (userSearch.value.trim() == '') {
    distributeUser();
  } else {
    userTreeData.value = userTreeData.value.filter((v: any) => {
      return v.label.indexOf(userSearch.value) > -1
    })
  }
  
}

</script>

<style scoped lang="scss">
.mainF {
  // display: flex;
  // .treeF {
  //   width: 15%;
  //   border: 1px solid #efefef;
  //   overflow-x: scroll;
  // }
  .tableF {
    // width: 85%;
    height: 100%;
  }
}

.distribution {
  margin-left: 10px;
  padding: 6px 11px;
  border: 1px solid $aside-active-color;
  background: #fff;
  color: #000;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  &:hover {
    background: $aside-active-color;
    color: #fff;
  }
}

.transformerBox {
  width: 100%;
  height: 500px;
  display: flex;
  .left_users, .right_roles {
    height: 100%;
    width: 50%;
    border: 1px solid rgb(225, 229, 237);
    margin-right: 15px;
    .title {
      background-color: #e1e5ed;
      padding: 15px;
    }
    .search {
      padding: 5px;
    }
    .userTree {
      padding: 20px;
    }
    .radios {
      padding: 5px;
      .radio-item {
        margin: 10px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>